<template>
  <div>
    <h2 class="form-tit-row">{{title}} <span v-if="max > 0">最多可上传{{max}}张</span></h2>
    <div class="form-wrap">
      <div class="form-wrap-row"
           v-if="max === 0 && imgList.length === 0">
        暂无图片
      </div>
      <div class="form-wrap-row"
           v-else>
        <ul class="pic-list cf">
          <li v-for="(item,index) in imgList">
            <img :src="item"
                 @click="PrevPic(item)">
            <i class="iconfont icon-del-black"
               @click="delImage(index)"
               v-if="max > 0"></i>
          </li>
          <div class="upload-btn"
               @click="getFlag()"
               v-if="max > 0">
            <i class="iconfont icon-add"></i>
          </div>
        </ul>
      </div>
    </div>

  </div>
</template>

<script>
import viewer from "@/components/share/ImageUploader/viewer.vue";
import { Previewer, TransferDom } from 'vux'
import { Indicator } from 'mint-ui';
export default {
  components: {
    viewer
  },
  props: {
    title: {
      type: String,
      required: true,
      default: '拍照或选择图片'
    },
    imgList: {
      type: Array,
      required: true,
      default: [],
    },
    max: {
      type: Number,
      required: true,
      default: 9,
    }
  },
  data () {
    return {
      showPrev: false,
      prevItem: {},
      filter: this.$options.filters,
      picount: 0,
      options: {
        getThumbBoundsFn (index) {
          // find thumbnail element
          let thumbnail = document.querySelectorAll('.previewer-demo-img')[index]
          // get window scroll Y
          let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
          // optionally get horizontal scroll
          // get position of element relative to viewport
          let rect = thumbnail.getBoundingClientRect()
          // w = width
          return { x: rect.left, y: rect.top + pageYScroll, w: rect.width }
          // Good guide on how to get element coordinates:
          // http://javascript.info/tutorial/coordinates
        }
      },
      list: [],
      imgseize: 0,
    }
  },
  methods: {
    PrevPic (item) {
      console.log(item)
      if (item.indexOf('base64') > -1) {
        this.prevItem = { Base64: item };
      } else {
        this.prevItem = { Url: item };
      }
      this.showPrev = !this.showPrev;
    },
    show (index) {
      console.log(this.list);
      this.$refs.previewer.show(index)
    },
    logIndexChange (arg) {
      console.log(arg)
    },
    delImage (i) {
      var self = this;
      self.imgList.splice(i, 1);
    },

    getFlag () {
      var self = this;
      let currentSize = this.imgList.length;
      self.picount = 0;
      if (currentSize >= this.max) {
        self.Toast({
          message: `最多只能上传${this.max}张图片！`,
        });
        return false;
      }

      this.jWeixin.chooseImage({
        count: 9, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          var localIds = res.localIds;
          console.log(localIds, 'localIds');
          if (self.imgList.length + localIds.length > self.max) {
            self.Toast({
              message: `最多只能上传${self.max}张图片！`,
            });
            return false;
          }
          self.picount = localIds.length;
          Indicator.open('正在上传图片....');
          // localIds.forEach((x, index) => {
          //   setTimeout(function () {
          //     self.getLocalImgData(x, index);
          //   }, 100);

          // });
          localIds.some(function (x, index) {
            setTimeout(function () {
              self.getLocalImgData(x, index);
            }, 100);
          });

          // }
        }
      });
    },
    getLocalImgData: function (i, index) {
      var self = this;

      this.jWeixin.getLocalImgData({
        localId: i, // 图片的localID
        success: function (res) {
          let localData = res.localData;
          //安卓兼容
          if (localData.indexOf('data:image') != 0) {
            localData = 'data:image/jpeg;base64,' + localData
          }
          //IOS兼容
          localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg');
          var prop = parseInt(Math.sqrt(localData.length / 102400 / 1.3));
          console.log(prop, '打印压缩比例');//打印压缩比例
          console.log("压缩前：" + localData.length / 1024 + "KB");
          if (prop > 3) {//若图片>100kb，即压缩比例>1，压缩图片
            self.compressedImg(localData, prop, index);//使用canvas压缩图片
          } else {//否则，可以直接使用该图片
            //localData = localData;
            self.imgList.push(localData);
            var imgData = {
              src: localData,
              w: 600,
              h: 400
            }
            self.list.push(imgData);
            if ((index + 1) == self.picount) {
              self.$emit('imgseizeSl', self.imgseize);
              Indicator.close();
            }
            console.log(res.localData);
          }

          console.log(self.imgList, '打印base64');//打印压缩比例
          //self.getLocalImgData(i + 1);

        }
      });
    },
    closeViewer () {
      this.showPrev = false;
      this.prevItem = {};
    },
    compressedImg (path, prop, index) {
      var self = this;
      var base64img = '';
      var img = new Image();
      img.src = path;
      img.onload = function () {
        var that = this;
        // 按压缩比例进行压缩
        var w = that.width / prop,
          h = that.height / prop;
        // console.log(w);
        // console.log(h);
        var quality = 1;  // 默认图片质量为1
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // quality值越小，所绘制出的图像越模糊
        var imgUrl = canvas.toDataURL('image/jpeg', quality);//压缩后的图片base64码

        self.imgseize = self.imgseize + (imgUrl.length / 1024);
        //parseFloat(self.imgseize / 1024).toFixed(2)
        console.log(parseFloat(self.imgseize / 1024).toFixed(2));
        if (parseFloat(self.imgseize / 1024).toFixed(2) > 4) {
          alert('图片大小不能超过4M');
          Indicator.close();
          return true;
        }
        self.imgList.push(imgUrl);
        if ((index + 1) == self.picount) {
          self.$emit('imgseizeSl', self.imgseize);
          Indicator.close();
        }


        console.log(imgUrl);//打印压缩后的图片base64码
        console.log("压缩后：" + imgUrl.length / 1024 + "KB");
        //return imgUrl;
      }
      return base64img;
    }
  }
}
</script>